//
//  GDUserRegisterController.m
//  GraduationDesign
//
//  Created by JiaKang.Zhong on 16/1/3.
//  Copyright © 2016年 JiaKang.Zhong. All rights reserved.
//

#import "GDUserRegisterController.h"
#import "GDUserAccountModel.h"
#import "GDUserLoginController.h"
#import "NSString+GDNumber.h"
#import "GDMainHomeController.h"
#import <BmobSDK/Bmob.h>
#import "MBProgressHUD+MJ.h"
@interface GDUserRegisterController ()<UIAlertViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITextFieldDelegate>
- (IBAction)backClick:(id)sender;
- (IBAction)registerClick:(id)sender;
@property (weak, nonatomic) IBOutlet UITextField *txtUserRegisterName;
@property (weak, nonatomic) IBOutlet UITextField *txtUserRegisterPwd;
@property (weak, nonatomic) IBOutlet UIButton *backItem;
@property (weak, nonatomic) IBOutlet UITextField *txtUseRegisterEmail;
@property (weak, nonatomic) IBOutlet UIImageView *userIconView;
@property (strong, nonatomic) IBOutlet UIView *backView;
@property (nonatomic,strong) NSData * icon_data;

@end
static int tempMask = 0;
@implementation GDUserRegisterController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.txtUserRegisterName.delegate = self;
    self.txtUserRegisterPwd.delegate = self;
    self.txtUseRegisterEmail.delegate = self;
    
#pragma mark 是否显示返回按钮
//    if (![GDUserAccountModel shareInstance].isRegister) {
//        self.backItem.hidden = YES;
//    }else{
//        self.backItem.hidden = NO;
//    }
 
    self.userIconView.userInteractionEnabled = YES;
    self.view.tag = 1;
    self.userIconView.tag = 2;
    UITapGestureRecognizer * tapGestureForView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClickCallBack:)];
    [self.view addGestureRecognizer:tapGestureForView];
    UITapGestureRecognizer * tapGestureForIcon = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClickCallBack:)];
    [self.userIconView addGestureRecognizer:tapGestureForIcon];
    
    //订阅通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHide:) name:UIKeyboardWillHideNotification object:nil];

    
    //更改cell里的图片
    self.userIconView.layer.masksToBounds = YES;
    self.userIconView.layer.cornerRadius = 40;
    self.userIconView.layer.borderWidth = 0.5;
    self.userIconView.layer.borderColor = [UIColor whiteColor].CGColor;
    
}


#pragma mark ******************* 键盘的位置或大小发生改变 *******************

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

    if (textField.tag == 2) {
        tempMask = 1;
    }else{
        tempMask = 0;
    }
    return YES;
}
- (void)keyBoardShow:(NSNotification *)notification{

       CGFloat duration = [notification.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] floatValue];
    if (tempMask) {
        GDLog(@"弹出");
        [UIView animateWithDuration:duration + 2 animations:^{
            self.view.transform = CGAffineTransformMakeTranslation(0, - 100);
        }];
    }else{
        [UIView animateWithDuration:duration animations:^{
            self.view.transform = CGAffineTransformMakeTranslation(0, 0);
        }];
    }
}

- (void)keyBoardHide:(NSNotification *)notification{
    
    if (tempMask) {
        CGFloat duration = [notification.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] floatValue];
        [UIView animateWithDuration:duration animations:^{
            self.view.transform = CGAffineTransformMakeTranslation(0, 0);
            
        }];
        tempMask = 0;
    }
}

-(void) tapClickCallBack:(UITapGestureRecognizer *) tapGes{
  
    NSLog(@"%ld",tapGes.view.tag);
    if (tapGes.view.tag == 1) {
        #pragma mark 关闭键盘
        [self.view endEditing:YES];
    }else if(tapGes.view.tag == 2) {
        #pragma mark 打开相册
        UIImagePickerController * pickerController = [[UIImagePickerController alloc] init];
        pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    pickerController.delegate = self;
    //允许编辑图片
    pickerController.allowsEditing = YES;
        [self presentViewController:pickerController animated:YES completion:nil];
    }
}

#pragma mark 图片选择器的代理
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    //获取修改后的图片
    UIImage *editedImg = info[UIImagePickerControllerEditedImage];
    NSData *_data = UIImageJPEGRepresentation(editedImg, 0.4f);
    long length = [_data length]/1000;
    if (length > 500) {
        _data = UIImageJPEGRepresentation(editedImg, 0.2f);
    }
    _icon_data = _data;
   self.userIconView.image = editedImg;
    //移除图片选择的控制器
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    UIColor * whiteColor = [UIColor whiteColor];
    [self.txtUserRegisterName setValue:whiteColor forKeyPath:@"_placeholderLabel.textColor"];
    [self.txtUserRegisterPwd setValue:whiteColor forKeyPath:@"_placeholderLabel.textColor"];
    [self.txtUseRegisterEmail setValue:whiteColor forKeyPath:@"_placeholderLabel.textColor"];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)prefersStatusBarHidden{
    return YES;
}

#pragma mark 返回按钮
- (IBAction)backClick:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark 注册按钮
- (IBAction)registerClick:(id)sender {
    NSString * u_name = self.txtUserRegisterName.text;
    NSString * u_pwd = self.txtUserRegisterPwd.text;
    NSString * u_email = self.txtUseRegisterEmail.text;

    
    if ([self judgeUserEnter]) {
        [MBProgressHUD showMessage:@"正在注册,请稍后"];
        //往GameScore表添加一条注册信息
        BmobObject *gameScore = [BmobObject objectWithClassName:@"GDUserAccount"];
        [gameScore setObject:u_name forKey:@"UserName"];
        [gameScore setObject:u_pwd forKey:@"UserPwd"];
        [gameScore setObject:u_email forKey:@"UserEmail"];
        [gameScore saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
            [MBProgressHUD hideHUD];
            NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
           [defaults setObject:u_name forKey:@"userName"];
              [defaults synchronize];
            //         保存用户信息
            [GDUserAccountModel initWithAccount:u_name withPwd:u_pwd withIcon:_icon_data];
            UIAlertView* alertView = [[UIAlertView alloc]
                                      initWithTitle:@"恭喜你,注册成功"
                                      message:nil
                                      delegate:self
                                      cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                      otherButtonTitles:nil];
            [alertView show];
        }];

        BmobFile *bmobFile = [[BmobFile alloc] initWithClassName:@"GDUserAccount" withFileName:[NSString stringWithFormat:@"%@.jpg",u_name]  withFileData:_icon_data];
        //如果文件保存成功，则把文件添加到filetype列
        [bmobFile saveInBackground:^(BOOL isSuccessful, NSError *error) {
            if (isSuccessful) {
               [gameScore setObject:bmobFile forKey:@"UserIcon"];
                NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
                [defaults setObject:bmobFile.url forKey:[NSString stringWithFormat:@"%@url",u_name]];
                   [defaults synchronize];
                GDLog(@"头像的url  %@",bmobFile.url);
            }
        } withProgressBlock:^(float progress) {
            GDLog(@"上传进度%.2f",progress);
        }];
    }

}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    GDMainHomeController * mainViewController = [[GDMainHomeController alloc] init];
    [self presentViewController:mainViewController animated:YES completion:nil];
}

#pragma mark 用户输入进行判断
-(BOOL) judgeUserEnter{
    BOOL result = false;
    if (self.txtUserRegisterName.text.length != 0 && self.txtUserRegisterPwd.text.length != 0
         ) {
        result = [self checkUserEnterEmail];
        if (!result) {
            ShowErrorAlert(@"邮箱格式不对");
        }
    }else{
        ShowErrorAlert(@"输入的长度不能为0");
    }
    return result;

}

#pragma mark 检查邮箱格式
-(BOOL) checkUserEnterEmail{
    BOOL result = false;
    NSString * email = self.txtUseRegisterEmail.text;
    if(email.length == 0 || [email isEqualToString:@""]){
        
        return result;
    }
    // 首字母不能是字母
    // 需要有@存在
    // 结尾是要.com
    if ([email hasSuffix:@".com"] && [email rangeOfString:@"@"].length != 0  &&
        [NSString isNumber:[email substringToIndex:1]]
        ) {
        result = true;
    }

    return result;
}





@end
